<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌首字母" prop="brandInitial" label-width="100px">
        <el-input
          v-model="queryParams.brandInitial"
          placeholder="请输入品牌的首字母"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['deal:brand:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['deal:brand:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['deal:brand:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['deal:brand:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌id" align="center" prop="brandId" v-if="false"/>
      <el-table-column label="品牌名称" align="center" prop="brandName" />
      <el-table-column align="center" prop="brandPic" label="品牌图片" width="160">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.brandPic" height="200" >
            <img slot="reference" :src="scope.row.brandPic" width="60" height="30"/>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="品牌的首字母" align="center" prop="brandInitial" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['deal:brand:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deal:brand:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌名称" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌图片">
          <imageUpload v-model="form.brandPic"/>
        </el-form-item>
        <el-form-item label="首字母" prop="brandInitial">
          <el-input v-model="form.brandInitial" placeholder="请输入品牌的首字母" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="关联分类">
          <el-checkbox v-model="categoryExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="categoryNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.categoryCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="categoryOptions"
            show-checkbox
            ref="category"
            node-key="id"
            :check-strictly="!form.categoryCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBrand, getBrand, delBrand, addBrand, updateBrand, exportBrand } from "@/api/deal/brand";
import { treeselect as categoryTreeselect, brandCategoryTreeselect } from "@/api/deal/category";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Brand",
  components: {
    ImageUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品牌管理表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      categoryExpand: false,
      categoryNodeAll: false,
      // 默认是0，0正常状态,1下线状态字典
      statusOptions: [],
      // 菜单列表
      categoryOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandName: undefined,
        brandPic: undefined,
        brandInitial: undefined,
        status: undefined,
        orderNum: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        brandName: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "默认是0，0正常状态,1下线状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询品牌管理列表 */
    getList() {
      this.loading = true;
      listBrand(this.queryParams).then(response => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getCategoryTreeselect() {
      categoryTreeselect().then(response => {
        this.categoryOptions = response.data;
      });
    },
    // 所有分类节点数据
    getCategoryAllCheckedKeys() {
      // 目前被选中的分类节点
      let checkedKeys = this.$refs.category.getCheckedKeys();
      // 半选中的分类节点
      let halfCheckedKeys = this.$refs.category.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据品牌ID查询分类树结构 */
    getBrandCategoryTreeselect(brandId) {
      return brandCategoryTreeselect(brandId).then(response => {
        this.categoryOptions = response.data.categories;
        return response;
      });
    },
    // 默认是0，0正常状态,1下线状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.category != undefined) {
        this.$refs.category.setCheckedKeys([]);
      }
      this.categoryExpand = false,
      this.categoryNodeAll = false,
      this.form = {
        brandId: undefined,
        brandName: undefined,
        brandPic: undefined,
        brandInitial: undefined,
        status: 0,
        orderNum: undefined,
        categoryIds: [],
        categoryCheckStrictly: true,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.brandId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.categoryOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.category.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.category.setCheckedNodes(value ? this.categoryOptions: []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.form.categoryCheckStrictly = value ? true: false;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryTreeselect();
      this.open = true;
      this.title = "添加品牌管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const brandId = row.brandId || this.ids
      const brandCategory = this.getBrandCategoryTreeselect(brandId);
      getBrand(brandId).then(response => {
        this.form = response.data;
        this.open = true;
        this.$nextTick(() => {
          brandCategory.then(res => {
            let checkedKeys = res.data.checkedKeys
            
            checkedKeys.forEach((v) => {
              this.$nextTick(()=>{
                this.$refs.category.setChecked(v, true ,false);
              })
            })
          });
        });
        this.title = "修改品牌管理";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.brandId != null) {
            this.form.categoryIds = this.getCategoryAllCheckedKeys();
            updateBrand(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.categoryIds = this.getCategoryAllCheckedKeys();
            addBrand(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const brandIds = row.brandId || this.ids;
      this.$confirm('是否确认删除品牌管理编号为"' + brandIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBrand(brandIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有品牌管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBrand(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
